# 断言
import copy

import pymysql
from pymysql import connect

from config import setting


class AssertUtil:
    # 链接数据库
    def connet_database(self):
        self.connect = pymysql.connect(
            user=setting.db_user,
            password=setting.db_password,
            host=setting.db_host,
            database=setting.db_database,
            port=setting.db_port

            # user = "sdm723416659",
            # password = "Msjy123456",
            # host = "sdm723416659.my3w.com",
            # database = "sdm723416659 db",
            # port = 3306
        )
        return self.connect

    # 执行sql
    def execute_sql(self,sql):
        # 创建数据库连接
        connect = self.connet_database()
        # 创建游标
        cursor = connect.cursor()
        # 执行sql
        cursor.execute(sql)
        # 取值
        value = cursor.fetchone()
        # 关闭资源
        cursor.close()
        connect.close()
        # 返回值
        return value

    def assert_all_case(self,res,assert_type,value):
        new_res = copy.deepcopy(res)
        # 把json()方法改成json属性，因为变成属性才能通过反射去获取属性的值
        try:
            new_res.json = new_res.json()
        except Exception:
            new_res.json = {"msg": '响应中无json数据'}

        # 循环判断断言
        for msg, anti_and_actual_data in value.items():
            # 属性名
            anticipate, actual = anti_and_actual_data[0], anti_and_actual_data[1]
            print(assert_type, msg, anticipate, actual)
            # 利用反射 属性名获取属性值（与提取变量原理一致）
            try:
                actual_value = getattr(new_res, actual)
                print(f"{actual}的属性值:{actual_value}")
            except Exception:
                actual_value = actual

            #判断断言是否相等
            match assert_type:
                case "equals":
                    assert  anticipate == actual_value, msg #msg能在断言出错时显示信息
                case "contains":
                    assert anticipate in actual_value, msg
                # 数据库断言
                case "db_equals":
                    antici_value = self.execute_sql(anticipate)
                    assert antici_value[0] == actual_value, msg
                case "db_contains":
                    antici_value = self.execute_sql(anticipate)
                    assert antici_value[0] in actual_value, msg

if __name__ == '__main__':
    value = AssertUtil().execute_sql("select email from tp_users where user_id = 1")
    print(value)